using System.Threading.Tasks;
using DesktopWidgetApp.Server.Models;
using DesktopWidgetApp.Server.API.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;

namespace DesktopWidgetApp.Server.API.Controllers
{
    /// <summary>
    /// 认证控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class AuthController : BaseController
    {
        private readonly IUserService _userService;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="userService">用户服务</param>
        public AuthController(IUserService userService)
        {
            _userService = userService;
        }

        /// <summary>
        /// 用户注册
        /// </summary>
        /// <param name="model">注册模型</param>
        /// <returns>注册结果</returns>
        [HttpPost("register")]
        public async Task<ActionResult>
        Register([FromBody] RegisterModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var (success, message, user) = await _userService.RegisterUserAsync(model.Username, model.Email, model.Password);

            if (!success)
            {
                return BadRequest(new { message });
            }

            return CreatedAtAction(nameof(GetCurrentUser), new { }, new { userId = user.Id, username = user.Username, email = user.Email });
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="model">登录模型</param>
        /// <returns>登录结果和JWT令牌</returns>
        [HttpPost("login")]
        public async Task<ActionResult>
        Login([FromBody] LoginModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var (success, message, token) = await _userService.LoginAsync(model.Username, model.Password);

            if (!success)
            {
                return BadRequest(new { message });
            }

            return Ok(new { token, message });
        }

        /// <summary>
        /// 获取当前登录用户信息
        /// </summary>
        /// <returns>用户信息</returns>
        [HttpGet("user/current")]
        [Authorize]
        public async Task<IActionResult> GetCurrentUser()
        {
            var userId = GetCurrentUserIdOrThrow();
            var user = await _userService.GetUserByIdAsync(userId);
            if (user == null)
            {
                return NotFound("用户不存在");
            }
            
            // 返回用户信息（不包含密码等敏感信息）
            var userDto = new
            {
                user.Id,
                user.Username,
                user.Email,
                user.Role,
                user.RegisteredAt,
                user.LastLoginAt
            };
            
            return Ok(userDto);
        }
        
        /// <summary>
        /// 刷新JWT令牌
        /// </summary>
        /// <param name="refreshTokenRequest">包含当前令牌和刷新令牌的请求</param>
        /// <returns>新的JWT令牌</returns>
        [HttpPost("token/refresh")]
        public async Task<IActionResult> RefreshToken([FromBody] RefreshTokenRequest refreshTokenRequest)
        {
            if (refreshTokenRequest == null || string.IsNullOrEmpty(refreshTokenRequest.Token) || string.IsNullOrEmpty(refreshTokenRequest.RefreshToken))
            {
                return BadRequest("无效的刷新令牌请求");
            }
            
            var result = await _userService.RefreshTokenAsync(refreshTokenRequest.Token, refreshTokenRequest.RefreshToken);
            if (!result.success)
            {
                return BadRequest(result.message);
            }
            
            return Ok(new { token = result.newToken });
        }
    }

    /// <summary>
    /// 注册模型
    /// </summary>
    public class RegisterModel
    {
        /// <summary>
        /// 用户名
        /// </summary>
        [System.ComponentModel.DataAnnotations.Required]
        [System.ComponentModel.DataAnnotations.StringLength(50, MinimumLength = 3)]
        public string Username { get; set; }

        /// <summary>
        /// 邮箱
        /// </summary>
        [System.ComponentModel.DataAnnotations.Required]
        [System.ComponentModel.DataAnnotations.EmailAddress]
        public string Email { get; set; }

        /// <summary>
        /// 密码
        /// </summary>
        [System.ComponentModel.DataAnnotations.Required]
        [System.ComponentModel.DataAnnotations.StringLength(100, MinimumLength = 6)]
        public string Password { get; set; }
    }

    /// <summary>
    /// 登录模型
    /// </summary>
    public class LoginModel
    {
        /// <summary>
        /// 用户名
        /// </summary>
        [System.ComponentModel.DataAnnotations.Required]
        public string Username { get; set; }

        /// <summary>
        /// 密码
        /// </summary>
        [System.ComponentModel.DataAnnotations.Required]
        public string Password { get; set; }
    }
}